import json
import os
import random

from django import http
from django.contrib.auth.mixins import LoginRequiredMixin
from django.core.paginator import Paginator
from django.shortcuts import render
from django.utils import timezone
from django.utils.timezone import now
from django.views import View
from django_redis import get_redis_connection

import constants
from apps.company.models import Company, CompanyDomain, Territory
from apps.company.utils import company_others, chaxun
from lagouwang.settings import STATICFILES_DIRS


class CompanyListView(View):
    """公司列表页"""

    def get(self, request, page_num):
        user = request.user

        try:
            territory = Territory.objects.all()
        except:
            return render(request, 'common/404.html')

        sort = request.GET.get('sort')

        fenleis = CompanyDomain.objects.filter(name=sort)

        company_id_list = []

        for fenlei in fenleis:
            company_id_list.append(fenlei.company_id)

        if sort == "default" or sort == None:
            sort = "default"
            sort_field = "create_time"
            companys = Company.objects.all().order_by(sort_field)
        else:
            if len(company_id_list) == 0:
                companys = None
            else:
                companys = Company.objects.filter(id__in=company_id_list)

        # 创建分页器
        paginator = Paginator(companys, constants.PAGE_NUM)
        try:
            page_com = paginator.page(page_num)
            total_page = paginator.num_pages
        except:
            page_com = None
            total_page = 1

        # 查询用户公司
        try:
            user_com = Company.objects.get(user_id=user.id)
        except:
            user_com = None
        context = {
            'user': user if user else None,
            'user_com': user_com,  # 用户的公司
            'territory': territory,  # 涉及领域
            'company': page_com,  # 分页后的数据
            'page_num': page_num,  # 当前页数
            'total_page': total_page,  # 总页数
            'sort': sort,  # 排序
        }

        return render(request, 'companylist.html', context)


class MyCompanyView(View):
    """我的公司"""

    def get(self, request):

        user = request.user
        try:
            company = Company.objects.get(user_id=user.id)
        except:
            return render(request, 'common/404.html')

        res = chaxun(company)
        # print("labels-------------", res.get("labels"))
        context = {
            'user': user if user else None,
            'company': company,
            'labels': res.get('labels'),
            'founder': res.get('founder'),
            'product': res.get('product'),
            'invest': res.get('invest'),
            'lingyu': res.get('lingyu'),
            'position': res.get('position'),
        }
        print("position", res.get('position').count())

        return render(request, 'myhome.html', context)


class CreateCompany(LoginRequiredMixin, View):
    """创建公司第一步"""

    def get(self, request):
        user = request.user

        context = {
            "user": user
        }

        return render(request, 'index01.html', context)

    def post(self, request):
        full_name = request.POST.get('fullname')  # 全称
        short_name = request.POST.get('shortname')  # 简称
        web_url = request.POST.get('website')  # 网址
        city = request.POST.get('city')  # 城市
        log_pic = request.FILES.get("companylog")  # 图片
        industry = request.POST.get('select_industry_hidden')  # 行业领域
        scale = request.POST.get('select_scale_hidden')  # 规模
        develop = request.POST.get('s_radio_hidden')  # 发展阶段
        invest = request.POST.get('select_invest_hidden')  # 投资组织发展阶段
        dev_stage = request.POST.get('stageorg')
        sketch = request.POST.get('temptation')

        # 上传公司log
        path = None
        if log_pic:
            path = os.path.join(STATICFILES_DIRS[0], 'company_images/' + log_pic.name)
            if log_pic.multiple_chunks():
                file_yield = log_pic.chunks()
                with open(path, 'wb') as f:
                    for buf in file_yield:
                        f.write(buf)
                    else:
                        print('大文件上传完毕')
            else:
                with open(path, 'wb') as f:
                    f.write(log_pic.read())
                print('小文件上传完毕')

        log_url = 'company_images/' + log_pic.name

        if not all([full_name, short_name, web_url, city, industry, scale, develop, sketch, log_pic]):
            return http.JsonResponse({"errno": constants.INFO_MISSING, 'errmsg': '信息未填写完整'})

        response = http.JsonResponse({'errno': constants.OK, 'errmsg': 'OK'})
        print("投资公司发展阶段", invest)
        print("投资公司名称", dev_stage)
        step1_cookie = {
            'full_name': full_name,
            'short_name': short_name,
            'web_url': web_url,
            'city': city,
            'log_url': log_url,
            'industry': industry,
            'scale': scale,
            'develop': develop,
            'invest': invest,
            'dev_stage': dev_stage,
            'sketch': sketch,
        }
        response.set_cookie('first_form', json.dumps(step1_cookie), max_age=15 * 24 * 3600)
        return response


class CreateCompanyTwo(LoginRequiredMixin, View):
    """第二步"""

    def get(self, request):
        user = request.user

        try:
            first_form = request.COOKIES['first_form']
        except:
            first_form = None
        print('第二步--------------')
        if not first_form:
            return render(request, 'common/404.html')
        context = {
            "user": user
        }

        return render(request, 'tag.html', context)

    def post(self, request):
        labels = request.POST.get('labels')

        if not labels:
            return http.JsonResponse({'errno': constants.INFO_MISSING, 'errmsg': '请为您的公司添加标签'})

        # 以列表的形式传给cookie
        labels_list = labels.split(',')

        response = http.JsonResponse({'errno': constants.OK, 'errmsg': 'OK'})
        response.set_cookie('tag', json.dumps(labels_list), max_age=15 * 24 * 3600)

        return response


class CreateCompanyThree(LoginRequiredMixin, View):
    """创建公司第三步"""

    def get(self, request):
        user = request.user
        try:
            first_form = request.COOKIES['first_form']
            tag = request.COOKIES['tag']
        except:
            first_form = None
            tag = None
        a = json.loads(first_form)
        b = json.loads(tag)

        if not all([first_form, tag]):
            return render(request, 'common/404.html')

        context = {
            "user": user
        }
        return render(request, 'founder.html', context)

    def post(self, request):
        name = request.POST.get('name')
        position = request.POST.get('position')
        weibo = request.POST.get('weibo')
        remark = request.POST.get('remark')
        founder_header = request.FILES.get("founder_header")
        # 上传公司log
        path = None
        if founder_header:
            path = os.path.join(STATICFILES_DIRS[0], 'company_images/founder/' + founder_header.name)
            if founder_header.multiple_chunks():
                file_yield = founder_header.chunks()
                with open(path, 'wb') as f:
                    for buf in file_yield:
                        f.write(buf)
                    else:
                        print('大文件上传完毕')
            else:
                with open(path, 'wb') as f:
                    f.write(founder_header.read())
                print('小文件上传完毕')
        print("走了------")
        founder_image = 'company_images/founder/' + founder_header.name

        if not all([name, position, weibo, remark]):
            return http.JsonResponse({'errno': constants.INFO_MISSING, 'errmsg': '请填写完整的信息'})
        founder_team = {
            'name': name,
            'position': position,
            'weibo': weibo,
            'remark': remark,
            'founder_image': founder_image,
        }
        print("创建团队----------------", founder_team)
        response = http.JsonResponse({'errno': constants.OK, 'errmsg': 'OK'})
        response.set_cookie('founder_team', json.dumps(founder_team), max_age=15 * 24 * 3600)

        return response


class CreateCompanyFour(LoginRequiredMixin, View):
    """创建公司第四步"""

    def get(self, request):
        user = request.user
        try:
            first_form = request.COOKIES['first_form']
            tag = request.COOKIES['tag']
            founder_team = request.COOKIES['founder_team']
        except:
            first_form = None
            tag = None
            founder_team = None
        a = json.loads(first_form)
        b = json.loads(tag)
        c = json.loads(founder_team)
        print(a)
        print(b)
        print(c)
        if not all([first_form, tag, founder_team]):
            return render(request, 'common/404.html')
        context = {
            "user": user,
        }

        return render(request, 'index02.html', context)

    def post(self, request):
        print(request.POST)
        name = request.POST.get('product')
        product_url = request.POST.get('productUrl')
        product_profile = request.POST.get('productProfile')
        product_pic = request.FILES.get("product_pic")  # 图片

        # 上传公司log
        path = None
        if product_pic:
            path = os.path.join(STATICFILES_DIRS[0], 'company_images/product_images/' + product_pic.name)
            if product_pic.multiple_chunks():
                file_yield = product_pic.chunks()
                with open(path, 'wb') as f:
                    for buf in file_yield:
                        f.write(buf)
                    else:
                        print('大文件上传完毕')
            else:
                with open(path, 'wb') as f:
                    f.write(product_pic.read())
                print('小文件上传完毕')

        poster_url = 'company_images/product_images/' + product_pic.name

        if not all([name, product_url, product_profile, product_pic]):
            return http.JsonResponse({'errno': constants.INFO_MISSING, 'errmsg': '请填写完整的产品信息'})

        product = {
            'name': name,
            'product_url': product_url,
            'product_profile': product_profile,
            'poster_url': poster_url,  # 产品海报
        }
        response = http.JsonResponse({'errno': constants.OK, 'errmsg': 'OK'})
        response.set_cookie('product', json.dumps(product), max_age=15 * 24 * 3600)

        return response


class CreateCompanyFive(LoginRequiredMixin, View):
    """创建公司第五步"""

    def get(self, request):
        user = request.user
        try:
            first_form = request.COOKIES['first_form']
            tag = request.COOKIES['tag']
            founder_team = request.COOKIES['founder_team']
            product = request.COOKIES['product']
        except:
            first_form = None
            tag = None
            founder_team = None
            product = None
        a = json.loads(first_form)
        b = json.loads(tag)
        c = json.loads(founder_team)
        d = json.loads(product)
        print(a)
        print(b)
        print(c)
        print(d)
        if not all([first_form, tag, founder_team, product]):
            return render(request, 'common/404.html')
        context = {
            "user": user
        }
        return render(request, 'index03.html', context)

    def post(self, request):
        user = request.user

        content = request.POST.get('companyProfile')

        if not content:
            return http.JsonResponse({'errno': constants.INFO_MISSING, 'errmsg': '请填写公司介绍'})
        try:
            first_form = json.loads(request.COOKIES['first_form'])
            tag = json.loads(request.COOKIES['tag'])
            founder_team = json.loads(request.COOKIES['founder_team'])
            product = json.loads(request.COOKIES['product'])
        except:
            return render(request, 'common/404.html')

        if not all([first_form, tag, founder_team, product]):
            return render(request, 'common/404.html')

        try:
            try:
                company = Company.objects.get(user_id=user.id)
            except:
                company = None

            if company != None:
                company = Company.objects.update(
                    full_name=first_form.get('full_name'),
                    short_name=first_form.get('short_name'),
                    log_url=first_form.get("log_url"),
                    web_url=first_form.get('web_url'),
                    city=first_form.get('city'),
                    scale=first_form.get('scale'),
                    dev_stage=first_form.get('develop'),
                    sketch=first_form.get('sketch'),
                    content=content,
                    user=user,
                    update_time=timezone.now().strftime("%Y-%m-%d %H:%I:%S"),
                )
            else:
                company = Company.objects.create(
                    full_name=first_form.get('full_name'),
                    short_name=first_form.get('short_name'),
                    log_url=first_form.get("log_url"),
                    web_url=first_form.get('web_url'),
                    city=first_form.get('city'),
                    scale=first_form.get('scale'),
                    dev_stage=first_form.get('develop'),
                    sketch=first_form.get('sketch'),
                    content=content,
                    user=user,
                    update_time=timezone.now().strftime("%Y-%m-%d %H:%I:%S"),
                )

        except:
            return http.JsonResponse({'errno': constants.DBERROR, 'errmsg': '创建失败'})

        # 公司其他信息写入数据库
        company_others(first_form, tag, founder_team, product, user)

        response = http.JsonResponse({'errno': constants.OK, 'errmsg': '创建成功'})
        response.delete_cookie('first_form')
        response.delete_cookie("tag")
        response.delete_cookie('founder_team')
        response.delete_cookie('product')

        # 储存到redis一个值返回成功页面
        redis_conn = get_redis_connection("status")
        # 建立管道
        print(user.id)
        status_id = "create_success%s" % user.id
        pl = redis_conn.pipeline()
        pl.set("create_success", status_id)
        pl.execute()

        return response


class CreateSucessView(LoginRequiredMixin, View):
    """成功页面"""

    def get(self, request):
        user = request.user

        try:
            redis_conn = get_redis_connection("status")
            success_status = redis_conn.get("create_success")
            success_status = success_status.decode()
            # print(success_status)
            if success_status != "create_success%s" % user.id:
                return render(request, "common/404.html")
            redis_conn.delete("create_success")
        except:
            return render(request, "common/404.html")
        # 获取当前用户公司
        try:
            user_com = Company.objects.get(user_id=user.id)
        except:
            return render(request, "common/404.html")
        context = {
            "user": user,  # 用户
            "user_com": user_com  # 当前用户公司
        }
        return render(request, "success.html", context)
